﻿using CoreWebApiNuGet.ApiContracts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using static CoreWebApiNuGet.ApiContracts.ApiResults;

namespace CoreWebApiNuGet.ActionFilter
{
    /// <summary>
    /// 全局异常处理过滤器
    /// </summary>
    public class ExceptionsActionFilter : IExceptionFilter
    {
        /// <summary>
        /// 重写发生异常处理方法
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (context.Exception is ApiException customException)
            {
                var customData = customException.BaseResultMsg;

                context.Result = context.Result = new ObjectResult(customData)
                {
                    StatusCode = (int)customData.ResultCode
                };
            }
            else
            {
                BaseResultMsg resultMsg = new BaseResultMsg();
                resultMsg.ResultCode = StatusCodes.Status500InternalServerError;
                resultMsg.ResultMsgs = "服务器被外星人绑架了,开发人员正在解救中！";//错误信息
                context.Result = new ObjectResult(resultMsg);
            }
        }
    }
}
